<%--
  Created by IntelliJ IDEA.
  User: cjbi
  Date: 2018/4/6
  Time: 7:43
  空页面.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<c:set var="path" value="${pageContext.request.contextPath}"/>

<!-- Content Header (Page header) -->
<section class="content-header" style="">
    <h1>
        账单管理
        <small>账单管理页面</small>
    </h1>
    <ol class="breadcrumb">
        <li><a href="#"><i class="fa fa-dashboard"></i> 主页</a></li>
        <li><a href="#">账单管理</a></li>
        <li class="active">系统用户管理</li>
    </ol>
</section>

<section class="content">
    <div class="row">
        <div class="col-xs-12">
            <div class="box">
                <!-- /.box-header -->
                <div class="box-body">
                    <div class="btn-group btn-group-sm" id="toolbar">
                        <!-- Provides extra visual weight and identifies the primary action in a set of buttons -->
                        <shiro:hasPermission name="bill:create">
                        <button type="button" id="addBtn" class="btn btn-default" data-toggle="modal"
                                data-target="#addModal"><i class="glyphicon glyphicon-plus"></i> 新增
                        </button>
                        </shiro:hasPermission>
                        <!-- Indicates caution should be taken with this action -->
                        <shiro:hasPermission name="bill:update">
                        <button type="button" id="editBtn" class="btn btn-default" data-toggle="modal"
                                data-target="#editModal"
                                data-action="{type:'editable',form:'#editForm',table:'#table',after:'editAfter'}"
                                disabled><i class="glyphicon glyphicon-edit"></i> 修改
                        </button>
                        </shiro:hasPermission>
                        <!-- Indicates a dangerous or potentially negative action -->
                        <shiro:hasPermission name="bill:delete">
                        <button type="button" id="deleteBtn" class="btn btn-default" data-toggle="modal"
                                data-target="#deleteModal"
                                data-action="{type:'delete',form:'#deleteForm',idField:'id',table:'#table'}" disabled><i
                                class="glyphicon glyphicon-remove"></i> 删除
                        </button>
                        </shiro:hasPermission>

                        <shiro:hasPermission name="bill:import">
                            <button type="button" id="importBtn" class="btn btn-default" data-toggle="modal"
                                    data-target="#importModal"
                                    ><i class="glyphicon glyphicon-chevron-up"></i> 导入
                            </button>
                        </shiro:hasPermission>
                        <!-- Indicates a dangerous or potentially negative action -->
                        <shiro:hasPermission name="bill:export">
                            <%--<a href="bill/exportExcel"  class="form-control">模板下载</a>--%>
                            <button type="button" id="exportBtn" class="btn btn-default" data-toggle="modal"
                                    data-target="#exportModal"
                                    class="glyphicon glyphicon-chevron-down"></i> 导出
                            </button>
                        </shiro:hasPermission>
                    </div>
                    <table id="table"></table>
                </div>
                <!-- /.box-body -->
            </div>
            <!-- /.box -->

        </div>
        <!-- /.col -->
    </div>
    <!-- /.row -->
</section>
<!-- /.content -->

<!-- add Modal -->
<div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="addModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="addModalLabel">添加账单</h4>
            </div>
            <div class="modal-body">
                <form id="addForm">
                    <div class="form-group">
                        <label class="control-label" for="cash"><span class="asterisk">*</span>金额:</label>
                        <input id="cash" type="number" class="form-control" name="cash" placeholder="输入金额"
                               minlength="3" required>
                        <div class="help-block with-errors"></div>
                    </div>
                    <div class="form-group">
                        <label class="control-label" for="ptype"><span class="asterisk">*</span>收支类型:</label>
                        <select name="ptype" id="ptype"  class="form-control chosen-select"
                                data-placeholder="请从列表选择一项" required>
                            <option value="收入">收入</option>
                            <option value="支出">支出</option>
                        </select>
                        <div class="help-block with-errors"></div>
                    </div>
                    <div class="form-group">
                        <label class="control-label" for="reason"><span
                                class="asterisk">*</span>事由:</label>
                        <input type="text" class="form-control" id="reason" minlength="2"
                                name="reason" placeholder="输入事由"
                               required>
                        <div class="help-block with-errors"></div>
                    </div>
                    <div class="form-group">
                        <label class="control-label" for="payment"><span class="asterisk">*</span>支付方式:</label>
                        <select name="payment" id="payment"  class="form-control chosen-select"
                                data-placeholder="请从列表选择一项" required>
                            <option value="现金">现金</option>
                            <option value="微信">微信</option>
                            <option value="支付宝">支付宝</option>
                            <option value="其他">其他</option>
                        </select>
                        <div class="help-block with-errors"></div>
                    </div>
                    <div class="form-group">
                        <label class="control-label" for="name"><span class="asterisk">*</span>姓名或称呼:</label>
                        <input type="text" class="form-control" id="name" name="name"
                               required>
                        <div class="help-block with-errors"></div>
                    </div>
                    <div class="form-group">
                        <label class="control-label" for="relationship"><span class="asterisk">*</span>关系:</label>
                        <input type="text" class="form-control" id="relationship" name="relationship"
                               required>
                        <div class="help-block with-errors"></div>
                    </div>

                    <div class="form-group">
                        <label class="control-label" for="pdate"><span class="asterisk">*</span>日期:</label>
                        <input type="date" class="form-control" id="pdate" name="pdate"
                               required>
                        <div class="help-block with-errors"></div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="submit" form="addForm" class="btn btn-primary"
                        data-action="{type:'submit',form:'#addForm',url:'<%=request.getContextPath()%>/bill/create',after:'$.myAction.refreshTable'}">
                    确定
                </button>
            </div>
        </div>
    </div>
</div>
<!-- edit Modal -->
<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="editModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="editModalLabel">修改账单</h4>
            </div>
            <div class="modal-body">
                <form id="editForm">
                    <input type="hidden" name="id"/>
                    <div class="form-group">
                        <label class="control-label" for="cash"><span class="asterisk">*</span>金额:</label>
                        <input id="editCash" type="text" class="form-control" name="cash" placeholder="输入金额"
                               minlength="3"  required>
                        <div class="help-block with-errors"></div>
                    </div>

                    <div class="form-group">
                        <label class="control-label" for="editPtype"><span class="asterisk">*</span>收支类型:</label>
                        <select name="ptype" id="editPtype"  class="form-control chosen-select"
                                data-placeholder="请从列表选择一项" required>
                           <%-- <c:forEach items="${roleList}" var="role">
                                <option value="${role.id}">${role.description}</option>
                            </c:forEach>--%>
                               <option value="收入">收入</option>
                               <option value="支出">支出</option>
                        </select>
                        <div class="help-block with-errors"></div>
                    </div>

                    <div class="form-group">
                        <label class="control-label" for="reason"><span class="asterisk">*</span>收支事由:</label>
                        <input type="text" class="form-control" id="editReason" name="reason"
                                required>
                        <input type="hidden" id="editOrganizationId" name="organizationId" required>
                        <div class="help-block with-errors"></div>
                    </div>
                    <div class="form-group">
                        <label class="control-label" for="editPayment"><span class="asterisk">*</span>支付方式:</label>
                        <select name="payment" id="editPayment"  class="form-control chosen-select"
                                data-placeholder="请从列表选择一项" required>
                           <%-- <c:forEach items="${roleList}" var="role">
                                <option value="${role.id}">${role.description}</option>
                            </c:forEach>--%>
                               <option value="现金">现金</option>
                               <option value="微信">微信</option>
                               <option value="支付宝">支付宝</option>
                               <option value="其他">其他</option>
                        </select>
                        <div class="help-block with-errors"></div>
                    </div>

                    <div class="form-group">
                        <label class="control-label" for="name"><span class="asterisk">*</span>姓名:</label>
                        <input type="text" class="form-control" id="editName" name="name"
                                required>

                        <div class="help-block with-errors"></div>
                    </div>

                    <div class="form-group">
                        <label class="control-label" for="relationship"><span class="asterisk">*</span>关系:</label>
                        <input type="text" class="form-control" id="editRelationship" name="relationship"
                                required>

                        <div class="help-block with-errors"></div>
                    </div>

                    <div class="form-group">
                        <label class="control-label" for="pdate"><span class="asterisk">*</span>收支时间:</label>
                        <input type="date" class="form-control" id="editDate" name="pdate"
                                required>
                        <div class="help-block with-errors"></div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="submit" form="editForm" class="btn btn-primary"
                        data-action="{type:'submit',form:'#editForm',url:'<%=request.getContextPath()%>/bill/update',after:'$.myAction.refreshTable'}">
                    确定
                </button>
            </div>
        </div>
    </div>
</div>

<!-- delete modal -->
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="deleteSmallModalLabel">
    <div class="modal-dialog modal-sm" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="deleteSmallModalLabel">删除用户</h4>
            </div>
            <div class="modal-body">
                <form id="deleteForm"></form>
                确定要删除选中的 <span class="records"></span> 条记录?
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" form="deleteForm" class="btn btn-primary"
                        data-action="{type:'submit',form:'#deleteForm',url:'<%=request.getContextPath()%>/bill/delete',after:'$.myAction.refreshTable'}">
                    确定
                </button>
            </div>
        </div>
    </div>
</div>

<!-- import modal -->
<div class="modal fade" id="importModal" tabindex="-1" role="dialog" aria-labelledby="importModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="importModalLabel">导入账单</h4>
            </div>
            <div class="modal-body">
                <form id="importForm" enctype="multipart/form-data" method="post" action="<%=request.getContextPath()%>/bill/importExcel" target="iframe_display">
                    <div class="form-group">
                        <label class="control-label" ><span class="asterisk">*</span>表格模板:</label>
                        <a href="bill/exportTemplate"  class="form-control">模板下载</a>
                    </div>
                    <div class="form-group">
                        <label class="control-label" for="file"><span class="asterisk">*</span>上传文件:</label>
                        <input type="file"  name="file"  id="file" class="form-control"/>
                        <div class="help-block with-errors"></div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="submit" form="importForm" class="btn btn-primary">
                    确定
                </button>
            </div>
        </div>
        <!-- 空iframe，用于协助处理form提交后不进行页面跳转的问题 -->
        <iframe id="iframe_display" name="iframe_display" style="display: none;"></iframe>
    </div>
</div>

<!-- zTree -->
<div id="menuContent" class="menuContent"
     style="display:none;z-index:1989101600;position: absolute;border: 1px solid #ccc; background-color: #fff;">
    <ul id="tree" class="ztree"></ul>
</div>
<script>

    var $table = $('#table');

    $(function () {
        // bootstrap table初始化
        // http://bootstrap-table.wenzhixin.net.cn/zh-cn/documentation/
        $table.bootstrapTable({
            url: path + '/bill/list',
            idField: 'id',
            searchOnEnterKey: false,
            sortable: true,          // 启用排序
            sortName: 'id',          // 默认排序字段
            sortOrder: 'asc',        // 默认排序方式
            sidePagination: 'server', // 服务器端分页
            columns: [
                {field: 'state', checkbox: true},
                {field: 'id', title: '编号', sortable: true, halign: 'left'},
                {field: 'name', title: '姓名', sortable: true, halign: 'left'},
                {field: 'relationship', title: '称呼', sortable: false, halign: 'left'},
                {field: 'cash', title: '金额', sortable: true, halign: 'left'},
                {field: 'ptype', title: '收支类型', sortable: false, halign: 'left'},
                {field: 'payment', title: '支付方式', sortable: false, halign: 'left'},
                {field: 'pdate', title: '日期', sortable: true, halign: 'left'},
                {field: 'reason', title: '收支事由', sortable: false, halign: 'left'},
                {
                    field: 'action',
                    title: '操作',
                    sortable:false,
                    halign: 'center',
                    align: 'center',
                    formatter: 'actionFormatter',
                    events: 'actionEvents',
                    clickToSelect: false
                }
            ]
        });


        $('#exportBtn').click(function() {
            $.ajax({
                url: 'bill/exportExcel',
                method: 'POST',
                xhrFields: {
                    responseType: 'blob' // 设置响应类型为blob
                },
                success: function(data) {
                    // 处理成功响应
                    var url = window.URL.createObjectURL(data); // 创建一个临时的URL对象
                    var a = document.createElement('a'); // 创建一个<a>元素
                    a.href = url; // 设置<a>元素的href属性为临时URL
                    a.download = 'bill.xls'; // 设置<a>元素的download属性为文件名 文件名自己改
                    document.body.appendChild(a)
                    a.click(); // 模拟点击<a>元素来触发下载
                    document.body.removeChild(a)
                    window.URL.revokeObjectURL(url); // 释放临时URL对象
                },
                error: function(xhr, status, error) {
                    // 处理错误响应
                    console.log('下载失败:', error);
                }
            });
        });

    });

    // 数据表格展开内容
    function detailFormatter(index, row) {
        var html = [];
        $.each(row, function (key, value) {
            html.push('<p><b>' + key + ':</b> ' + value + '</p>');
        });
        return html.join('');
    }

    function editAfter(obj,row) {
        var roleIdList = row.roleIdList;
        for (i in roleIdList) {
            var roleId = roleIdList[i];
            $('#editForm').find('[name=roleIds]').find('option[value=' + roleId + ']').prop('selected', true);
        }
        $.myAdmin.refreshComponent();
    }

    function actionFormatter(value, row, index) {
        return '\
        <a class="like" href="javascript:void(0)" data-toggle="tooltip" title="Like"><i class="glyphicon glyphicon-heart"></i></a>　\
        <shiro:hasPermission name="bill:update">\
        <a class="edit ml10" href="javascript:void(0)" data-toggle="tooltip" title="编辑"><i class="glyphicon glyphicon-edit"></i></a>　\
        </shiro:hasPermission>\
        <shiro:hasPermission name="bill:delete">\
        <a class="remove ml10" href="javascript:void(0)" data-toggle="tooltip" title="删除"><i class="glyphicon glyphicon-remove"></i></a>　\
        </shiro:hasPermission>\
        ';
    }

    window.actionEvents = {
        'click .like': function (e, value, row, index) {
            alert('You click like icon, row: ' + JSON.stringify(row));
            console.log(value, row, index);
        },
        'click .edit': function (e, value, row, index) {
            $('#editModal').modal('show')
            $('#editForm').fillForm(row);
            editAfter('',row);
            console.log(value, row, index);
        },
        'click .remove': function (e, value, row, index) {
            $('#deleteModal').modal('show');
            $('.records').html('1');
            var html = '';
            for (var key in row) {
                html += '<input type="hidden" name="' + key + '" value="' + row[key] + '">';
            }
            $('#deleteForm').html(html);
        }
    };

    var setting = {
        view: {
            dblClickExpand: false
        },
        data: {
            simpleData: {
                enable: true
            }
        },
        callback: {
            onClick: onClick
        }
    };

    var zNodes = [
        <c:forEach items="${organizationList}" var="o">
        <c:if test="${not o.rootNode}">
        {id:${o.id}, pId:${o.parentId}, name: "${o.name}"},
        </c:if>
        </c:forEach>
    ];

    function onClick(e, treeId, treeNode) {
        var zTree = $.fn.zTree.getZTreeObj("tree"),
            nodes = zTree.getSelectedNodes(),
            id = "",
            name = "";
        nodes.sort(function compare(a, b) {
            return a.id - b.id;
        });
        for (var i = 0, l = nodes.length; i < l; i++) {
            id += nodes[i].id + ",";
            name += nodes[i].name + ",";
        }
        if (id.length > 0) id = id.substring(0, id.length - 1);
        if (name.length > 0) name = name.substring(0, name.length - 1);
        $("#organizationId").val(id);
        $("#organizationName").val(name);
        $("#editOrganizationId").val(id);
        $("#editOrganizationName").val(name);
        hideMenu();
    }

    function showMenu() {
        var cityObj = $("#organizationName");
        var cityOffset = $("#organizationName").offset();
        $("#menuContent").css({
            left: cityOffset.left + "px",
            top: cityOffset.top + cityObj.outerHeight()
        }).slideDown("fast");

        $("body").bind("mousedown", onBodyDown);
    }

    function showMenuOfEdit() {
        var cityObj = $("#editOrganizationName");
        var cityOffset = $("#editOrganizationName").offset();
        $("#menuContent").css({
            left: cityOffset.left + "px",
            top: cityOffset.top + cityObj.outerHeight()
        }).slideDown("fast");

        $("body").bind("mousedown", onBodyDown);
    }

    function hideMenu() {
        $("#menuContent").fadeOut("fast");
        $("body").unbind("mousedown", onBodyDown);
    }

    function onBodyDown(event) {
        if (!(event.target.id == "organizationName" || event.target.id == "menuContent" || $(event.target).parents("#menuContent").length > 0)) {
            hideMenu();
        }
    }

    $.fn.zTree.init($("#tree"), setting, zNodes);
    $("#organizationName").click(showMenu);
    $("#editOrganizationName").click(showMenuOfEdit);
</script>